<template>
  <div class="purchase">
    <!-- {{ getData.editTimer }} -->
    <div class="purchase_header">
      <p>编辑定时订单</p>
      <el-button @click="handelClickBack">返回</el-button>
    </div>
    <div class="purchase_supply_information">
      <p>供应商信息</p>
      <div class="purchase_supply_information_message">
        <div>
          <p>企业名称</p>
          <p>{{ getData.editTimer.factorName }}</p>
        </div>
        <div>
          <p>跟单人员</p>
          <p>{{ getData.editTimer.trackerName }}</p>
        </div>
        <div>
          <p>跟单人电话</p>
          <p>{{ getData.editTimer.trackerTel }}</p>
        </div>
        <div>
          <p>工厂地址</p>
          <p>{{ getData.editTimer.factorAddress }}</p>
        </div>
      </div>
    </div>
    <!-- {{ getData.editTimer.list }} -->
    <div class="purchase_commodity_information">
      <p>商品信息</p>
      <el-table :data="getData.editTimer.list" border style="width: 100%" @select="handelChange" @select-all="handelSelectAll">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="商品信息" width="480">
          <template #default="scope">
            <div class="sp_message">
              <div>
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div>
                <p>{{ scope.row.factorName }}</p>
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码:{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.businessSkuId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="supplyUnitPrice" label="供应单价" />
        <el-table-column prop="buyNum" label="数量" />
        <el-table-column prop="buyPartNum" label="商品件数" />
        <el-table-column prop="" label="折扣率(%)">
          <template #default="scope">
            <el-input-number
              style="width: 100px"
              :controls="false"
              :min="0"
              :max="100"
              v-model="scope.row.discountRate"
              @input="handleChangeDiscountRate(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="" label="折扣(元)">
          <template #default="scope">
            {{ scope.row.discountAmount }}
            <!-- <el-input-number
              style="width: 100px"
              :min="0"
              :max="scope.row.supplyUnitPrice"
              :controls="false"
              v-model="scope.row.discountAmount"
            ></el-input-number> -->
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="采购实付价格">
          <template #default="scope">
            <el-input-number
              style="width: 100px"
              :min="0"
              :step="0.1"
              :max="scope.row.supplyUnitPrice * scope.row.commodityNum"
              :controls="false"
              v-model="scope.row.actualAmount"
              @input="handelInputActualAmount(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部表单信息 -->
    <div class="purchase_form">
      <div class="purchase_form-left">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <div v-if="data.num == 2 || data.num == 3">
            <el-form-item label="定时采购时间" prop="">
              <el-date-picker
                v-model="getData.editTimer.autoPurchaseTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="datetime"
                placeholder="日期"
                style="width: 100%"
              />
            </el-form-item>
          </div>
          <!-- <el-form-item label="收款账户选择" prop="">
            <el-input></el-input>
          </el-form-item> -->
          <el-form-item label="设置定时采购时间" prop="">
            <!-- <el-date-picker
              v-model="getData.editTimer.autoPurchaseTime"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="datetime"
              placeholder="日期"
              style="width: 100%"
            /> -->
            <el-date-picker
              v-model="getData.editTimer.autoPurchaseTime"
              type="datetime"
              placeholder="请选择"
              date-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              @change="handleautoPurchaseTime"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="期望到货日期" prop="">
            <!-- <el-date-picker
              v-model="getData.editTimer.expectedDeliveryTime"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="datetime"
              placeholder="日期"
              style="width: 100%"
            /> -->
            <el-date-picker
              v-model="getData.editTimer.expectedDeliveryTime"
              type="datetime"
              placeholder="请选择"
              date-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              @change="handleexpectedDeliveryTime"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="发货类型" prop="">
            <div style="width: 100%">
              <el-radio-group v-model="getData.editTimer.receivingType" @change="handelChangeReceivingType">
                <el-radio value="1">收货仓库</el-radio>
                <el-radio value="2">直发客户</el-radio>
              </el-radio-group>
            </div>
            <div class="warehouse_content" v-if="getData.editTimer.receivingType == 1">
              <el-select
                v-model="getData.editTimer.receivingWarehouseId"
                placeholder="请选择仓库"
                @change="handelChangeWarehouse"
              >
                <el-option
                  v-for="(item, index) in data.warehouseList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="其他费用">
            <el-input v-model="getData.editTimer.otherFee" placeholder="" @input="handelInputsOtherFee"></el-input>
            <!-- <el-input-number v-model="getData.editTimer.otherFee" style="width: 100%" :controls="false"></el-input-number> -->
          </el-form-item>
          <el-form-item label="优惠金额">
            <!-- <el-input-number v-model="getData.editTimer.discountAmount" style="width: 100%" :controls="false"></el-input-number> -->
            <el-input v-model="getData.editTimer.discountAmount" placeholder="" @input="handelInputsDiscountAmount"></el-input>
          </el-form-item>
          <el-form-item label="订单说明">
            <!-- <el-input v-model="getData.editTimer.remark" type="textarea"></el-input> -->
            <RemarkEditor v-model="getData.editTimer.remark" />
          </el-form-item>
          <el-form-item label="附件">
            <!-- <el-upload
              v-model:file-list="FileList"
              action="https://dev.51jzt.com/dev-api/mall/tenant/merchant/order/excel/import"
              :headers="{
                Authorization: `Bearer ${getLocalCache(globalConfig.tokenAttr)}`
              }"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList);
                }
              "
            >
              <el-icon><Plus /></el-icon>
            </el-upload> -->
            <!-- {{ imgFileList }} -->
            <el-upload
              class="upload-demo"
              v-model:file-list="imgFileList"
              ref="uploadImg"
              :show-file-list="true"
              multiple
              :limit="10"
              list-type="text"
              :auto-upload="false"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList);
                }
              "
              :on-preview="
                file => {
                  reviewFile(file);
                }
              "
            >
              <template #trigger>
                <el-button :disabled="FileList.length >= 10" style="width: 100%; height: 100%">
                  <el-icon class="f24"><Plus /></el-icon>
                </el-button>
              </template>
              <template #tip>
                <p class="f12 mt10" style="color: #86909c">支持doc/docx/pdf/jpg，最多上传10个。</p>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="purchase_form-right">
        <div class="purchase_form-right-top" v-if="getData.editTimer.receivingType == 1">
          <p>收货信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ getData.editTimer.receivingName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ getData.editTimer.receivingMobile }}</p>
          </div>
          <div>
            <p style="display: flex; align-items: center">
              收货地址:<span
                style="color: #007dff; margin-left: 6px; cursor: pointer; margin: 0 10px"
                @click="handelClickChangeAdess"
                >修改 </span
              ><el-icon color="#007DFF" size="20" @click="handelClickChangeAdess"><Edit /></el-icon>
            </p>
            <p>{{ getData.editTimer.receivingAreaDetail }}</p>
            <!-- <div >
              <el-cascader
                style="width: 100%"
                v-model="data.receivingAreaIds"
                :options="chinas"
                clearable
                @change="handelChnageCity"
              />
              <p>详细地址</p>
              <el-input v-model="detaileditTimerect.receivingAreaDetail"></el-input>
            </div> -->
          </div>
        </div>
        <div class="purchase_form-right-botton">
          <p>买家信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ getData.editTimer.customerName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ getData.editTimer.customerMobileCode }}</p>
          </div>
          <div>
            <p>项目地址:</p>
            <p>{{ getData.editTimer.customerAddress }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="botton_btn">
      <div class="left">
        <p>
          优惠金额：¥<span>{{ getData.editTimer.discountAmount }}</span>
        </p>
        <p>
          其他费用：¥<span>{{ getData.editTimer.otherFee }}</span>
        </p>
        <p>
          商品总价：¥<span>{{ data.commodityTotal }}</span>
        </p>
        <p>
          应付金额：<span>¥{{ data.payTotal }}</span>
        </p>
      </div>
      <div class="right">
        <el-button type="primary" style="margin-left: 10px" @click="handelClickClearTimer">清除定时</el-button>
        <el-button type="" @click="handelClickBack">取消</el-button>
        <el-button type="primary" @click="handelClickCreateProcure"> 确定定时采购设置 </el-button>
      </div>
    </div>
    <!-- 清除定时弹窗 -->
    <dialog-View :isShow="data.isShowClearTime" :width="'50%'">
      <div class="time_content">
        <el-icon size="50" color="red"><Warning /></el-icon>
        <p>您正在执行清除定时采购设置，清除后，此条定时采购计划将被请清除，需要手动进行发起采购，是否继续？</p>
      </div>
      <div class="clear_btn">
        <el-button @click="data.isShowClearTime = false">取消</el-button>
        <el-button type="primary" @click="onclickSbmitClear">确定</el-button>
      </div>
    </dialog-View>
    <!-- 发布采购单成功弹窗 -->
    <dialog-View :isShow="data.isPurchaseOrder" :width="'50%'">
      <div class="procure_success">
        <div><img src="@/static/images/suceess.png" /></div>
        <div>您已成功将当前订单合同发起采购单，采购明细可前往采购单查看 ~</div>
        <div>
          <el-button @click="handelClickClose">关闭</el-button>
          <el-button type="primary" @click="handelClickGo">前往查看</el-button>
        </div>
      </div>
    </dialog-View>
    <!-- 修改地址弹框 -->
    <dialog-View :isShow="data.isShowOrderAdress" :title="'修改地址'" :width="'30%'">
      <form-View
        :formList="data.formListOrderAdess"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        @update="handelUpdateAdess"
        @back="handelBackAdess"
      ></form-View>
    </dialog-View>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
// import { getLocalCache } from "@/utils/cache";
// import globalConfig from "@/settings";
import { Warning, Edit } from "@element-plus/icons-vue";
import china from "@/utils/china.json";
import dayjs from "dayjs";
import { roundDecimal, mathRound } from "@/utils/summation";
import { initiateProcurement } from "@/store/index";
import {
  // getOrderDetail,
  // createPurchase,
  // createTimingPurchase,
  delTimingPurchase,
  updateTimingPurchase
} from "@/apis/order/index";
import { getlistByTenantId } from "@/apis/procure/index";
import {
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { ElMessage } from "element-plus";
// 组件导入
import dialogView from "../components/dialogView.vue";
import formView from "../components/formView.vue";
import RemarkEditor from "@/components/RemarkEditor";
// 获取存储数据
const chinas = ref(china);
const getData = initiateProcurement();
const useRout = useRouter();
const useRoutes = useRoute();
const ruleFormRef = ref();
const ruleForm = ref({
  otherFee: 0,
  discountAmount: 0,
  warehouseId: ""
});
const rules = ref({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  ]
});
const data = reactive({
  orderId: "",
  num: 1, //1代表普通采购单，2代表定时采购单
  list: [
    { name: "sdsdsd1", mark: "mark", num: 20, jian: 30, zkl: "30%", zk: 20, pic: 999 },
    { name: "sdsdsd2", mark: "mark", num: 20, jian: 30, zkl: "30%", zk: 20, pic: 999 }
  ],
  totalPic: 0,
  // 清除定时
  isShowClearTime: false,
  // 清除定时-------end
  isPurchaseOrder: false,
  // 仓库数据
  warehouseList: [],
  warehouseCopyList: [],
  receivingAreaIds: [],
  // 仓库数据-------end,
  // 带过来的数据
  orderDetails: {},
  // 修改地址
  isShowOrderAdress: false,
  // 修改地址------------
  formListOrderAdess: [
    { label: "收货人", model: "receivingName", type: "input" },
    { label: "手机", model: "receivingMobile", type: "input" },
    { label: "收货地址", model: "receivingAreaIds", type: "cascader", options: chinas },
    { label: "详细地址", model: "receivingAreaDetail", type: "input" }
  ],
  rulesOrderAdess: {
    receivingName: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 1, max: 200, message: "请输入名称", trigger: "blur" }
    ],
    receivingMobile: [
      { required: true, message: "请输入电话", trigger: "blur" },
      { min: 1, max: 200, message: "请输入电话", trigger: "blur" }
    ],
    receivingAddress: [
      {
        required: true,
        message: "请选择地址",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            return callback(new Error("请选择一个地址"));
          }
          return callback();
        }
      }
    ],
    receivingAreaDetail: [
      { required: true, message: "请输入详细地址", trigger: "blur" },
      { min: 1, max: 300, message: "请输入详细地址", trigger: "blur" }
    ]
  },
  // 商品总价
  commodityTotal: 0,
  payTotal: 0,
  copyDataRsal: {}
});
const handelInputsOtherFee = () => {
  getData.editTimer.otherFee = getData.editTimer.otherFee.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
const handelInputsDiscountAmount = () => {
  getData.editTimer.discountAmount = getData.editTimer.discountAmount.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
// 定时时间转换
const handleautoPurchaseTime = value => {
  getData.editTimer.autoPurchaseTime = value;
  getData.editTimer.autoPurchaseTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
};
// 定时时间转换
const handleexpectedDeliveryTime = value => {
  getData.editTimer.expectedDeliveryTime = value;
  getData.editTimer.expectedDeliveryTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
};
// 修改地址
const handelClickChangeAdess = () => {
  data.isShowOrderAdress = true;
};
const handelBackAdess = () => {
  data.isShowOrderAdress = false;
};
const handelUpdateAdess = (item, adres) => {
  console.log(item, adres);
  data.isShowOrderAdress = false;
  getData.editTimer.receivingName = item.receivingName;
  getData.editTimer.receivingAreaDetail = adres + item.receivingAreaDetail;
  getData.editTimer.receivingMobile = item.receivingMobile;
  getData.editTimer.receivingAreaIds = item.receivingAreaIds;
};

// 修改折扣率
const picData = ref(0);
const handleChangeDiscountRate = item => {
  console.log(item);
  let arr = JSON.stringify(getData.editTimer.list);
  let copyTabelList = JSON.parse(arr);
  console.log(copyTabelList, "222222");
  // return
  // setTimeout(() => {
  //   copyTabelList.map(it => {
  //     if (it.businessSkuId === item.businessSkuId) {
  //       picData.value = it.actualPrice;
  //     }
  //   });
  //   let total = Number(item.commodityNum) * Number(item.supplyUnitPrice) * (Number(item.discountRate) / 100); //实际价格
  //   let zkTotal =
  //     Number(item.commodityNum) * Number(item.supplyUnitPrice) -
  //     Number(item.commodityNum) * Number(item.supplyUnitPrice) * (Number(item.discountRate) / 100); //则扣总价
  //   console.log(total, zkTotal, Number(item.discountRate) / 100);
  //   const ddiscountAmount = roundDecimal(zkTotal / Number(item.commodityNum), 2);
  //   item.discountAmount = ddiscountAmount;
  //   item.actualPrice = total;
  //   publicTotal();
  // });
  setTimeout(() => {
    copyTabelList.map(it => {
      if (it.businessSkuId === item.businessSkuId) {
        picData.value = it.supplyUnitPrice;
      }
    });
    let total = Number(item.buyNum) * Number(item.supplyUnitPrice) * (Number(item.discountRate) / 100); //实际价格
    let zkTotal =
      Number(item.buyNum) * Number(item.supplyUnitPrice) -
      Number(item.buyNum) * Number(item.supplyUnitPrice) * (Number(item.discountRate) / 100); //则扣总价
    const ddiscountAmount = roundDecimal(zkTotal / Number(item.buyNum), 2);
    console.log(ddiscountAmount, "ddiscountAmount");
    item.discountAmount = ddiscountAmount;
    // item.actualPrice = total;
    item.actualAmount = roundDecimal(total, 2);
    publicTotal();
  }, 0);
};
const handelInputActualAmount = item => {
  setTimeout(() => {
    item.discountRate = mathRound((item.actualAmount / item.buyNum / item.supplyUnitPrice) * 100);
    let zkTotal =
      Number(item.buyNum) * Number(item.supplyUnitPrice) -
      Number(item.buyNum) * Number(item.supplyUnitPrice) * (Number(item.discountRate) / 100); //则扣总价
    const ddiscountAmount = roundDecimal(zkTotal / Number(item.buyNum), 2);
    item.discountAmount = ddiscountAmount;
    getpayTotal();
  }, 0);
};
// 求和
const productInfos = ref([]);
function publicTotal() {
  // const sum = productInfos.value.reduce((accumulator, currentObject) => {
  //   return Number(accumulator) + Number(currentObject.unitPrice);
  // }, 0);
  // data.commodityTotal = sum;
  // getpayTotal();
  const sum = productInfos.value.reduce((accumulator, currentObject) => {
    return Number(accumulator) + Number(currentObject.supplyUnitPrice * currentObject.buyNum);
  }, 0);
  data.commodityTotal = sum;
  getpayTotal();
}
// 应付总金额
const getpayTotal = () => {
  // data.payTotal = Number(data.commodityTotal) - Number(getData.editTimer.discountAmount) + Number(getData.editTimer.otherFee);
  const sum = productInfos.value.reduce((accumulator, currentObject) => {
    return Number(accumulator) + Number(currentObject.actualAmount);
  }, 0);
  data.payTotal = sum - Number(getData.editTimer.discountAmount) + Number(getData.editTimer.otherFee);
};
// 监听优惠金额和其他费用的变化
watch(
  () => [getData.editTimer.otherFee, getData.editTimer.discountAmount],
  () => {
    getpayTotal();
  },
  { deep: true, immediate: true }
);
// 发起定时采购单
const handelClickCreateProcure = () => {
  const arrFiles = [];
  // 处理上传文件
  imgFileList.value.map(it => {
    console.log(it);
    arrFiles.push(it.fileUrl);
  });
  // return
  const {
    receivingType,
    receivingWarehouseId,
    receivingName,
    receivingMobile,
    receivingAreaIds,
    receivingAreaDetail,
    receivingAddress,
    expectedDeliveryTime,
    otherFee,
    discountAmount,
    remark,
    // attachmentFileUrls,
    autoPurchaseTime
  } = getData.editTimer;
  // console.log(attachmentFileUrls, "attachmentFileUrls");
  // return
  let params = {
    purchaseOrderId: getData.editTimer.timingPurchaseOrders[0]?.purchaseOrderId,
    orderId: getData.editTimer.timingPurchaseOrders[0]?.orderId,
    productInfos: productInfos.value,
    payInfoId: "",
    receivingType,
    receivingWarehouseId,
    receivingName,
    receivingMobile,
    receivingAreaIds: typeof receivingAreaIds == "string" ? receivingAreaIds : receivingAreaIds.join(","),
    receivingAreaDetail,
    receivingAddress,
    expectedDeliveryTime,
    otherFee,
    discountAmount,
    remark,
    attachmentFileUrls: arrFiles.join(","),
    autoPurchaseTime
    // shopPurchaseOrderDetail:"111"
  };
  updateTimingPurchase(params).then(res => {
    if (res.code == 200) {
      data.isPurchaseOrder = true;
    }
  });
  console.log(params, "ppppp");
};
const handelClickClearTimer = () => {
  data.isShowClearTime = true;
};
// 上传
import { imgsUpload } from "@/apis/products/specifications";
import { getFolder } from "@/utils/index";
const FileList = ref([]); //商品图片list
const uploadImg = ref();
const imgFileList = ref([]); //编辑时商品图片list
const imgIsReady = ref(true);
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img-word") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img-word" ? _fileList : [file]);
  if (!flag) {
    if (type === "img-word") {
      ElMessage({
        message: "支持扩展名：doc/docx/pdf/jpg",
        type: "error",
        offset: 60
      });
      const errorFile = _fileList.filter(
        item =>
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf"
          )
      );
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    return;
  }
  if (type === "img-word") {
    FileList.value = fileList;
    imgIsReady.value = false;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
    imgIsReady.value = true;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "img-word") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img-word") {
        item["fileUrl"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
// 返回
const handelClickBack = () => {
  useRout.push({
    path: "/oder/detail",
    query: {
      orderId: useRoutes.query.orderId
    }
  });
};
// 多选框事件

const handelChange = item => {
  productInfos.value = item;
  publicTotal();
};
// 表格全选事件
const handelSelectAll = item => {
  productInfos.value = item;
  publicTotal();
};
const onclickSbmitClear = () => {
  delTimingPurchase({
    purchaseOrderId: getData.editTimer.timingPurchaseOrders[0].purchaseOrderId
  }).then(() => {
    ElMessage({
      message: "清楚定时采购单成功",
      type: "success"
    });
    setTimeout(function () {
      useRout.push({
        path: "/oder"
      });
    }, 1000);
  });
};
// 前往采购单列表页
const handelClickGo = () => {
  useRout.push({
    path: "/procure/purchase-order"
  });
};
// 关闭
const handelClickClose = () => {
  data.isPurchaseOrder = false;
};
// 获取仓库信息
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    data.warehouseList = arr;
    data.warehouseCopyList = res.data;
  });
};
const receiptInformation = ref({});
const handelChangeWarehouse = v => {
  let obj = {};
  data.warehouseCopyList.map(it => {
    if (v == it.warehouseId) {
      console.log(it);
      getData.editTimer.receivingName = it.manageUserName;
      getData.editTimer.receivingMobile = it.managePhoneNo;
      getData.editTimer.receivingAreaIds = it.provinceId + "," + it.cityId + "," + it.districtId;
      getData.editTimer.receivingAreaDetail = it.address;
      getData.editTimer.receivingAddress = it.address;
    }
  });
  receiptInformation.value = obj;
};
const handelChangeReceivingType = v => {
  console.log(v, data.copyDataRsal);
  // return
  if (v == 2) {
    console.log("jin");
    getData.editTimer.receivingName = data.copyDataRsal.receivingName;
    getData.editTimer.receivingMobile = data.copyDataRsal.receivingMobile;
    getData.editTimer.receivingAreaIds = data.copyDataRsal.receivingAreaIds;
    getData.editTimer.receivingAreaDetail = data.copyDataRsal.receivingAreaDetail;
    getData.editTimer.receivingAddress = data.copyDataRsal.receivingAddress;
  }
};
watch(
  () => getData.editTimer.receivingType,
  n => {
    console.log(n, "---------");
    if (n == 1) {
      getData.editTimer.receivingName = "";
      getData.editTimer.receivingMobile = "";
      getData.editTimer.receivingAddress = "";
      getData.editTimer.receivingAreaIds = "";
      getData.editTimer.receivingAreaDetail = "";
      // getData.editTimer.receivingWarehouseId = "";
    }
  },
  { deep: true }
);
onMounted(() => {
  if (Object.keys(getData.editTimer).length == 0) {
    let obj2 = window.sessionStorage.getItem("purchaseEditTime");
    getData.editTimer = JSON.parse(obj2);
  }
  // 回显附件文件
  let filts = getData.editTimer.attachmentFileUrls.split(",");
  let arr = [];
  filts.map(it => {
    arr.push({
      url: it,
      fileUrl: it,
      name: decodeURI(it).split("/")[decodeURI(it).split("/").length - 1]
    });
  });
  imgFileList.value = arr;
  // ---------------------end
  getlistByTenantIds();
  const copyData = JSON.stringify(getData.editTimer);
  const copyDataRsalt = JSON.parse(copyData);
  data.copyDataRsal = copyDataRsalt;
  // publicTotal();
  chinas.value.map(item => {
    // 第一层
    item.label = item.name;
    item.value = item.cityCode;
    // eslint-disable-next-line no-prototype-builtins
    if (item.hasOwnProperty("children")) {
      console.log("第二层");
      // 第二层
      item.children.map(citem => {
        citem.label = citem.name;
        citem.value = citem.cityCode;
        // eslint-disable-next-line no-prototype-builtins
        if (citem.hasOwnProperty("children")) {
          // 第三层
          citem.children.map(ccitem => {
            ccitem.label = ccitem.name;
            ccitem.value = ccitem.cityCode;
          });
        }
      });
    }
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
